<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="130px">
      <el-form-item label="申请人(主创)学号" prop="userId">
        <el-input v-model="dataForm.userId" placeholder="申请人(主创)学号" @blur="getStuInfo()"></el-input>
      </el-form-item>
      <!--      自动查询-->
      <el-form-item label="申请人姓名">
        <el-input v-model="dataForm.useName" placeholder="申请人姓名" disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="院系">
        <el-input v-model="dataForm.yuanxi" placeholder="院系" disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="dataForm.banji" placeholder="班级" disabled="true"></el-input>
      </el-form-item>

      <el-form-item label="申请内容" prop="txt">
        <el-input v-model="dataForm.txt" placeholder="申请内容"></el-input>
      </el-form-item>
      <el-form-item label="申请材料" prop="ossUrl">
        <!--      <el-input v-model="dataForm.ossUrl" placeholder="申请材料地址"></el-input>-->
        <SingleUpload v-model="dataForm.ossUrl"></SingleUpload>
      </el-form-item>
      <!--      <el-form-item label="提交时间" prop="tijiaoTime">-->
      <!--        <el-input v-model="dataForm.tijiaoTime" placeholder="提交时间"></el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="审批时间" prop="shenpiTime">-->
      <!--        <el-input v-model="dataForm.shenpiTime" placeholder="审批时间"></el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="审批人" prop="shenpiUser">-->
      <!--        <el-input v-model="dataForm.shenpiUser" placeholder="审批人"></el-input>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="是否通过1:通过 0:待通过 -1:未通过" prop="pass">-->
      <!--        <el-input v-model="dataForm.pass" placeholder="是否通过1:通过 0:待通过 -1:未通过"></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item label="项目类型" prop="xiangmuId">
        <!--        <el-input v-model="dataForm.xiangmuId" placeholder="项目类型id"></el-input>-->
        <el-cascader @change="getXiangmuInfo()"
                     filterable
                     placeholder="请选择"
                     v-model="xiangmuId"
                     :options="categories"
                     :props="props"></el-cascader>
      </el-form-item>


      <el-form-item label="年级">
        <el-select v-model="nianji" placeholder="请选择年级" @change="neww(nianji)">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请选择你的铁驭 (不要选你自己)">
        <template>
          <el-transfer v-model="part" :data="data" :titles="['未选', '已选']"></el-transfer>
        </template>
      </el-form-item>
      <el-form-item label="分数组成">
        <el-input v-model="dataForm.getfen" placeholder="请以 1,2,3 格式分配分数 注意分数和为上值"
                  @blur="yanzheng()"></el-input>
      </el-form-item>
      <el-form-item label="剩余分数">
        {{ this.shengyu }}
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="test()">测试</el-button>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <!--    <template>-->
    <!--      <el-select v-model="value" placeholder="请选择">-->
    <!--        <el-option-->
    <!--          v-for="item in options"-->
    <!--          :key="item.value"-->
    <!--          :label="item.label"-->
    <!--          :value="item.value">-->
    <!--        </el-option>-->
    <!--      </el-select>-->
    <!--    </template>-->
  </el-dialog>
</template>

<script>
import SingleUpload from '../../../components/upload/singleUpload.vue'

export default {
  components: {SingleUpload},
  data () {
    const nianjiData = _ => {
      const data = []
      for (let i = 2019; i <= 2029; i++) {
        data.push({
          key: `${i}`,
          label: `${i}级`
        })
      }
      return data
    }
    return {
      groupIdtrue: 0,
      all: 999,
      shengyu: 9999,
      used: [],
      data: [],
      part: [],
      nianji: '',
      options: [
        {value: '2022', label: '2022级'},
        {value: '2023', label: '2023级'}
      ],
      // options: [{
      //   value: '选项1',
      //   label: '黄金糕'
      // }, {
      //   value: '选项2',
      //   label: '双皮奶'
      // }, {
      //   value: '选项3',
      //   label: '蚵仔煎'
      // }, {
      //   value: '选项4',
      //   label: '龙须面'
      // }, {
      //   value: '选项5',
      //   label: '北京烤鸭'
      // }],
      // value: '',
      props: {
        value: 'id',
        label: 'name',
        children: 'childrenCategories'
      },
      visible: false,
      categories: [],
      xiangmuId: [],
      dataForm: {
        getfen: '',
        listTree: '',
        id: 0,
        userId: '',
        txt: '',
        ossUrl: '',
        tijiaoTime: '',
        shenpiTime: '',
        shenpiUser: '',
        pass: '',
        xiangmuId: '',
        userName: '',
        status: '',
        yuanxi: '',
        banji: '',
      },
      dataRule: {
        userId: [
          {required: true, message: '申请人(主创)学号不能为空', trigger: 'blur'}
        ],
        txt: [
          {required: true, message: '申请内容不能为空', trigger: 'blur'}
        ],
        ossUrl: [
          {required: true, message: '申请材料地址不能为空', trigger: 'blur'}
        ],
        tijiaoTime: [
          {required: true, message: '提交时间不能为空', trigger: 'blur'}
        ],
        shenpiTime: [
          {required: true, message: '审批时间不能为空', trigger: 'blur'}
        ],
        shenpiUser: [
          {required: true, message: '审批人不能为空', trigger: 'blur'}
        ],
        pass: [
          {required: true, message: '是否通过1:通过 0:待通过 -1:未通过不能为空', trigger: 'blur'}
        ],
        xiangmuId: [
          {required: true, message: '项目类型id不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.getXiangmuListTree()
    this.data = []
  },
  methods: {
    yanzheng () {
      var arr = this.dataForm.getfen.split(',')
      var sum = 0
      for (var i = 0; i < arr.length; i++) {
        sum += parseInt(arr[i])
      }
      if (sum != this.shengyu || arr.length != this.part.length) {
        this.$message({
          message: '分数组成不合法',
          type: 'error'
        })
      } else {
        this.$message({
          message: '分数组成合法',
          type: 'success'
        })
      }
    },
    getXiangmuInfo () {
      console.log(this.xiangmuId)
      this.$http({
        url: this.$http.adornUrl(`/stu/xiangmutypelevel/info/${this.xiangmuId[this.xiangmuId.length-1]}`),
        method: 'get'
      }).then(({data}) => {
        console.log(data)
        this.shengyu = data.xiangmuTypeLevel.fenshuGroup - data.xiangmuTypeLevel.fenshuZhuchi
        this.all = data.xiangmuTypeLevel.fenshuZhuchi
        // this.dataForm.userName = data.xiangmu.userName
        // this.dataForm.yuanxi = data.xiangmu.yuanxi
        // this.dataForm.banji = data.xiangmu.banji
      })
    },
    test () {
      console.log(this.part)
    },
    neww (nianji) {
      this.getUsersByNianji(nianji)
    },
    getUsersByNianji (nianji) {
      // this.data=this.used.slice(0)
      this.$http({
        url: this.$http.adornUrl(`/stu/users/getUserByNianji/${nianji}`),
        menubar: 'get'
      }).then(({data}) => {
        console.log(data)
        // this.data=data.users
        for (var i = 0; i < data.users.length; i++) {
          this.data.push(data.users[i])
        }
        // console.log(this.data)
        // 去重处理
        if (typeof this.used[0] === 'object') {
          // 对象数组去重
          this.data = this.removeDuplicates(this.data)
        } else {
          // 基本类型数组去重
          this.data = Array.from(new Set(this.data))
        }

        for (var i = 0; i < this.data.length; i++) {
          if (this.data[i].key == this.dataForm.userId) {
            this.data[i].disabled = true
          }
        }
        console.log(this.data)
      })
    },
// 对象数组去重方法
    removeDuplicates (arr) {
      const seen = new Set()
      return arr.filter(item => {
        const key = JSON.stringify(item)
        if (seen.has(key)) {
          return false
        }
        seen.add(key)
        return true
      })
    },
    getXiangmuListTree () {
      this.$http({
        // url: 'http://localhost:9090/commodity/category/list/tree',
        url: this.$http.adornUrl('/stu/xiangmutypelevel/list/groupTree'),
        menubar: 'get'
      }).then(({data}) => { //解构 获得下一层的data
        console.log(data.listTree)
        this.categories = data.listTree
      })
    },
    getStuInfo () {
      //查询dataForm.userId学号对应的信息info
      console.log(this.dataForm.userId)
      this.$http({
        url: this.$http.adornUrl(`/stu/users/info/${this.dataForm.userId}`),
        menubar: 'get'
      }).then(({data}) => { //解构 获得下一层的data
        console.log(data)
        this.dataForm.useName = data.users.username
        this.dataForm.yuanxi = data.users.yuanxi
        this.dataForm.banji = data.users.banji
      })
    },
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/stu/shenqingroup/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.userId = data.shenqinGroup.userId
              this.dataForm.txt = data.shenqinGroup.txt
              this.dataForm.ossUrl = data.shenqinGroup.ossUrl
              // this.dataForm.tijiaoTime = data.shenqinGroup.tijiaoTime
              // this.dataForm.shenpiTime = data.shenqinGroup.shenpiTime
              // this.dataForm.shenpiUser = data.shenqinGroup.shenpiUser
              // this.dataForm.pass = data.shenqinGroup.pass
              this.dataForm.xiangmuId = data.shenqinGroup.xiangmuId
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      console.log(this.dataForm)
      console.log(this.xiangmuId)
      this.dataForm.xiangmuId = this.xiangmuId[this.xiangmuId.length - 1]
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/stu/shenqingroup/save`),
            method: 'post',
            data: this.$http.adornData({
              'userId': this.dataForm.userId,
              'txt': this.dataForm.txt,
              'ossUrl': this.dataForm.ossUrl,
              // 'tijiaoTime': this.dataForm.tijiaoTime,
              // 'shenpiTime': this.dataForm.shenpiTime,
              // 'shenpiUser': this.dataForm.shenpiUser,
              // 'pass': this.dataForm.pass,
              'xiangmuId': this.dataForm.xiangmuId
            })
          }).then(({data}) => {
            console.log(data)
            if (data && data.code === 0) {
              this.groupIdtrue = data.id
              this.newGroup()
              this.$message({
                message: '项目创建成功',
                type: 'success',
                duration: 1500,
                // onClose: () => {
                //   this.visible = false
                //   this.$emit('refreshDataList')
                // }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    //新建组长
    newGroup () {
      console.log(this.groupIdtrue)
      this.$http({
        url: this.$http.adornUrl(`/stu/shenqingroupstudents/save`),
        method: 'post',
        data: this.$http.adornData({
          'groupId': this.groupIdtrue,
          'userId': this.dataForm.userId,
          'isLeader': 1,
          'fenshu': this.all,
        })
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 0) {
          this.$message({
            message: '组长创建成功',
            type: 'success',
          })
          this.newGroupPeople()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    newGroupPeople(){

      for (var i = 0; i < this.part.length; i++) {
        this.$http({
          url: this.$http.adornUrl(`/stu/shenqingroupstudents/save`),
          method: 'post',
          data: this.$http.adornData({
            'groupId': this.groupIdtrue,
            'userId': this.part[i],
            'isLeader': 0,
            'fenshu': this.dataForm.getfen.split(',')[i],
          })
        }).then(({data}) => {
          console.log(data)
          if (data && data.code === 0) {
            this.$message({
              message: `组员${this.part[i]}创建成功`,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    }
//
//     for(var i=0;i<this.part;i++){
//   this.$http({
//     url: this.$http.adornUrl(`/stu/shenqingroupstudents/save`),
//     method: 'post',
//     data: this.$http.adornData({
//       'groupId': groupId,
//       'userId': this.part[i],
//       'isLeader': 0,
//       'fenshu': this.dataForm.getfen.split(',')[i],
//     })
//   }).then(({data}) => {
//     console.log(data)
//     if (data && data.code === 0) {
//       this.$message({
//         message: `组员${this.part[i]}创建成功`,
//         type: 'success',
//         duration: 1500,
//         onClose: () => {
//           this.visible = false
//           this.$emit('refreshDataList')
//         }
//       })
//     } else {
//       this.$message.error(data.msg)
//     }
//   })
// }

  }
}
</script>
